package com.waverider.promotion.biz.dao.ibatis;

import java.sql.SQLException;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.waverider.promotion.biz.dao.ShopDAO;
import com.waverider.promotion.domain.ShopDO;

public class ShopDAOImpl implements ShopDAO
{
	
	private SqlMapClient sqlMapClient;
	
	@Override
	public void insert(ShopDO shop)
	{
		try
		{
			sqlMapClient.insert("shop.dao.insert", shop);
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}

	@Override
	public ShopDO queryBySellerId(Long sellerId)
	{
		try
		{
			return (ShopDO)sqlMapClient.queryForObject("shop.dao.queryBySellerId", sellerId);
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public ShopDO queryByShopId(Long shopId)
	{
		try
		{
			return (ShopDO)sqlMapClient.queryForObject("shop.dao.queryByShopId", shopId);
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	@Override
	public boolean update(ShopDO shop)
	{
		try
		{
			sqlMapClient.startTransaction();
			int rows = sqlMapClient.update("shop.dao.update", shop);
			
			if(rows > 1)
			{
				throw new RuntimeException("[ERROR] Not possible!");
			}
			
			sqlMapClient.commitTransaction();
			
			if(rows == 1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			try
			{
				sqlMapClient.endTransaction();
			}
			catch (SQLException e)
			{
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public boolean delete(Long id)
	{
		try
		{
			sqlMapClient.startTransaction();
			int rows = sqlMapClient.delete("shop.dao.delete", id);
			
			if(rows > 1)
			{
				throw new RuntimeException("[ERROR] Not possible!");
			}
			
			sqlMapClient.commitTransaction();
			
			if(rows == 1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch(SQLException e)
		{
			throw new RuntimeException(e);
		}
		finally
		{
			try
			{
				sqlMapClient.endTransaction();
			}
			catch (SQLException e)
			{
				throw new RuntimeException(e);
			}
		}
	}

	public void setSqlMapClient(SqlMapClient sqlMapClient)
	{
		this.sqlMapClient = sqlMapClient;
	}
}
